package com.roger.bt.trans.ser;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.roger.bt.trans.ser.service.ReceiveService;
import com.roger.bt.trans.ser.service.SendService;
import com.roger.bt.trans.ser.util.GetFile;
import java.io.File;
import java.util.Set;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends AppCompatActivity {

    public static BluetoothDevice device;
    private Set<BluetoothDevice> bondedDevices;
    private EditText name;
    private TextView file;
    public static String tarDevice,tarFile ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission(this);
        name = findViewById(R.id.device);
        file = findViewById(R.id.file);
        initBT();
    }

    private void initBT() {
        BluetoothManager btManger = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter btAdapter = btManger.getAdapter();
        if (btAdapter == null) {
            Toast.makeText(MainActivity.this, "Device not support BT !", Toast.LENGTH_SHORT).show();
        } else {
            if(!btAdapter.isEnabled()) btAdapter.enable();
            bondedDevices = btAdapter.getBondedDevices();
            if(bondedDevices.size()==1){
                for(BluetoothDevice d : bondedDevices)
                    name.setText(d.getName());
            }
        }
    }

    public void send(View v){
        tarDevice = name.getText().toString();
        tarFile = file.getText().toString();
        boolean isDevice = false;
        for(BluetoothDevice d : bondedDevices){
            if (d.getName().equals(tarDevice)) {
                device = d;
                isDevice=true;
            }
        }

        File f = new File(tarFile);
        boolean isFile = f.exists() && f.length() > 0 && f.isFile();

        if(!isDevice) Toast.makeText(this,"No paired name found",Toast.LENGTH_SHORT).show();
        if(!isFile) Toast.makeText(this,"File not found",Toast.LENGTH_SHORT).show();

        if( isDevice && isFile ){
            Toast.makeText(this,"start send file service ",Toast.LENGTH_SHORT).show();
            Intent intent=new Intent (MainActivity.this,SendService.class);
            if( Build.VERSION.SDK_INT>=Build.VERSION_CODES.O ) startForegroundService(intent);
            else startService(intent);
        }
    }

    public void receive(View v){
        Toast.makeText(this,"start receive service",Toast.LENGTH_SHORT).show();
        Intent intent=new Intent (MainActivity.this,ReceiveService.class);
        if( Build.VERSION.SDK_INT>=Build.VERSION_CODES.O ) startForegroundService(intent);
        else startService(intent);
    }

    protected void checkPermission(AppCompatActivity activity) {
        boolean isGranted = true;
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
            if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ) {
                isGranted = false;
            }
            if (!isGranted) {
                activity.requestPermissions(
                        new String[]{
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        }, 102);
            }
        }
    }

    @SuppressLint("WakelockTimeout,InvalidWakeLockTag")
    public static void wakeLock(Context c){
        PowerManager pm = (PowerManager)c.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myService");
        wl.acquire();
    }

    public void file(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, Activity.RESULT_FIRST_USER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String path;
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri !=null && "file".equalsIgnoreCase(uri.getScheme())){
                path = uri.getPath();
                file.setText(path);
                return;
            }
            path = GetFile.getPath(this, uri);
            File f = new File(path);
            if(f.length()==0){
                file.setText("this file is not support!");
            }else{
                file.setText(path);
            }
        }
    }
}
